<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\facade\Log;

/**
 * 关键应用接口
 */
class Application extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = [];

    public function data()
    {
        //处理参数
        $type = $this->request->post('type');
        if(!$type){
            $this->error(__('Missed parameters'));
        }
        if(!in_array($type, config('application')['type'])){
            $this->error(__('Invalid parameters'));
        }
        $appid = $this->request->post('appid');
        if(!$appid){
            $this->error(__('Missed parameters'));
        }
        $dpi = $this->getDpi();
        $apps = isset($dpi['apps'])? $dpi['apps']: '';
        if(!$apps){
            $this->error(__('Please configure the dpi apps'));
        }
        $appids = array();
        $appid_names = array();
        if(is_array($apps) && count($apps) > 0){
            foreach ($apps as $key => $value) {
                if(!isset($value['appid']) || !isset($value['appname'])){
                    $this->error(__('Please configure the dpi apps'));
                }
                $appids[] = $value['appid'];  
                $appid_names[$value['appid']] = $value['appname'];  
            }
        }else{
            $this->error(__('Please configure the dpi apps'));
        }
        if(!in_array($appid, $appids) ){
            $this->error(__('Invalid parameters'));
        }
        switch ($type) {
            case 'flow':
                $input_arr = array(
                    "hours"=>24,
                    "tmend"=>0,
                    "tag"=>'bps',
                    "appid"=>$appid,
                    "bridge"=>0
                );
                break;
            case 'link':
                $input_arr = array(
                    "hours"=>24,
                    "tmend"=>0,
                    "tag"=>'flow',
                    "appid"=>$appid,
                    "bridge"=>0
                );
                break;
            case 'snap':
                $input_arr = array(
                    "refresh"=>0,
                    "statype"=>'all',
                    "tag"=>'flow',
                    "topn"=>20,
                    "appid"=>$appid,
                    "appname"=>$appid_names[$appid],
                );
                break;
            default:
                # code...
                break;
        }

        $data_string = http_build_query($input_arr);
        $cookie_jar = $this->getPanabitCookieJar();
        //发请求拿数据
        $curlopt = array(
            // CURLOPT_HTTPHEADER=>array ('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen ( $data_string ) ),
            CURLOPT_SSL_VERIFYPEER=>0,
            CURLOPT_SSL_VERIFYHOST=>FALSE,
            CURLOPT_TIMEOUT=>config('application')['timeout'],
            CURLOPT_COOKIEFILE=>$cookie_jar,
        );
        $dpi = $this->getDpi();
        if($type == 'snap'){
            $url = $dpi['url'].config('application')['url_html'];
        }else{
            $url = $dpi['url'].config('application')['url'];
        }

        Log::record(microtime().'发送dpi地址：'.$url,'API');
        Log::record(microtime().'发送dpi参数：'.$data_string,'API');
        $data = curl_post($url, $data_string, $curlopt);
        Log::record(microtime().'dpi接口返回：'.$data,'API');
        if($type != 'snap'){
           $data = iconv('gb2312', 'utf-8', $data); 
        }

        if(strpos($data, config('panabit')['content_error'] ) !== false ){
            //重新登录，重新获取数据
            $cookie_jar = $this->getPanabitCookieJar(1);
            Log::record(microtime().'发送dpi地址：'.$url,'API');
            Log::record(microtime().'发送dpi参数：'.$data_string,'API');
            $data = curl_post($url, $data_string, $curlopt);
            Log::record(microtime().'dpi接口返回：'.$data,'API');
            if($type != 'snap'){   
                $data = iconv('gb2312', 'utf-8', $data);
            }
             if(strpos($data, config('panabit')['content_error'] ) !== false ){
                $this->error(__('Data Access failed, please try again later'));
             }
        }
        if($type == 'flow' || $type == 'link'){
            $data = str_replace("'", '"', $data);
            $data_arr = json_decode($data,true);
        }else if($type == 'snap'){
            //匹配 开始<tr id=row1 height=22>结尾</tr>的一段html
            $partern = '/<tr id=row1 height=22>(.*?)<\/tr>/ism';
            preg_match($partern,$data,$result);
            $partern =  '/<td align=right>(.*?)<\/td>/ism';
            if(isset($result[1])){
                preg_match_all($partern,$result[1],$result); 
            }
            $data_arr = array();
            $data_arr['flow_up_down'] = isset($result[1][2])? $result[1][2]: '';
            $data_arr['speed_up_down'] = isset($result[1][3])? $result[1][3]: '';
        }
        $this->success('', $data_arr);
    }

    public function topn(){
         $input_arr = array(
            "title"=>"",
            "refresh"=>0,
            "topn"=>config('application')['topn_url_number'],
            "group"=>"",
            "bridge"=>"",
            "statype"=>'all',
        );
        $data_string = http_build_query($input_arr);
        $cookie_jar = $this->getPanabitCookieJar();
        //发请求拿数据
        $curlopt = array(
            // CURLOPT_HTTPHEADER=>array ('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen ( $data_string ) ),
            CURLOPT_SSL_VERIFYPEER=>0,
            CURLOPT_SSL_VERIFYHOST=>FALSE,
            CURLOPT_TIMEOUT=>config('application')['timeout'],
            CURLOPT_COOKIEFILE=>$cookie_jar,
        );
        $dpi = $this->getDpi();
        $url = $dpi['url'].config('application')['topn_url'];
        Log::record(microtime().'发送dpi地址：'.$url,'API');
        Log::record(microtime().'发送dpi参数：'.$data_string,'API');
        $data = curl_post($url, $data_string, $curlopt);
        Log::record(microtime().'dpi接口返回：'.$data,'API');
        $data = iconv('gb2312', 'utf-8', $data); 

        if(strpos($data, config('panabit')['content_error'] ) !== false ){
            //重新登录，重新获取数据
            $cookie_jar = $this->getPanabitCookieJar(1);
            Log::record(microtime().'发送dpi地址：'.$url,'API');
            Log::record(microtime().'发送dpi参数：'.$data_string,'API');
            $data = curl_post($url, $data_string, $curlopt);
            Log::record(microtime().'dpi接口返回：'.$data,'API');  
            $data = iconv('gb2312', 'utf-8', $data);
             if(strpos($data, config('panabit')['content_error'] ) !== false ){
                $this->error(__('Data Access failed, please try again later'));
             }
        }

        //匹配流量
        $partern = '/<tr id=row5>(.*?)<\/tr>/ism';
        preg_match_all($partern,$data,$result);
        $flows = array();
        if(isset($result[1])){
            foreach ($result[1] as $key => $value) {
                if($key%2 == 1){
                    continue; //10分钟流量过滤掉
                }
                $partern =  '/<td width=80 align=right>(.*?)<\/td>/ism';
                $result2 = array();
                preg_match_all($partern,$value,$result2); 
                $flows[] = isset($result2[1][0]) ? $result2[1][0] : '';
            }
        }
        // echo '<pre>';print_r($flows);

        //匹配appid和appname
        $partern = '/<a href="javascript:showapp(.*?)>/ism';
        preg_match_all($partern,$data,$result);
        if(isset($result[1])){
            $apps = array();
            $app_names = array();
            foreach ($result[1] as $key => $value) {
                $value = str_replace("('", '', $value);
                $value = str_replace("')", '', $value);
                $value_arr = explode("', '", $value);
                $item = array();
                $item['appid'] = isset($value_arr[0]) ? $value_arr[0] : '';
                $item['appname'] = isset($value_arr[1]) ? $value_arr[1] : '';
                $item['appname'] = str_replace('"', '', $item['appname']);
                $app_names[] = $item['appname'];
                $apps[] = $item;
            }
        }
        // echo '<pre>';print_r($app_names);

        //根自己库里的app对比，拿出top10
        $db_app_names = $this->get_apps('appname');
        // echo '<pre>';print_r($db_app_names);
        //取交集
        $has_flow_app = array_intersect($app_names, $db_app_names);
        // echo '<pre>';print_r($has_flow_app);
        //取top10
        $top_has_flow_app = array_slice($has_flow_app,0,config('application')['top_number'], true);
        // echo '<pre>';print_r($top_has_flow_app);
        $data_arr = array();
        //拼最终结果
        $db_name_appname = $this->get_apps('appname_name');
        foreach ($top_has_flow_app as $key => $value) {
            $item = array();
            $item['name'] = isset($db_name_appname[$value]) ? $db_name_appname[$value] : '未知';
            $item['text'] = $flows[$key];
            $item['value'] = conversion_unit($item['text']);
            $data_arr[] = $item;
        }
        $this->success('', $data_arr);
    }

}
